package com.atguigu.yygh.gateway.filter;
/*
用户认证过滤器
 */

import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

//@Component //将全局过滤器放到ioc容器
public class UserAuthenticationFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();//路径匹配器


    @Override
    //拦截的业务逻辑
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//获取请求报文
        String value = request.getPath().value();//将请求路径转换成String类型
        ServerHttpResponse response = exchange.getResponse();//获取响应报文

        boolean match = antPathMatcher.match("/admin/user/**", value);//判断请求路径是否为admin/user开头
        //匹配放行,不匹配拦截
        if(match){
            return chain.filter(exchange);//放行
            //判断是否慰问admin开头,是说明想访问管理员相关接口
        }else if(antPathMatcher.match("/admin/**",value)){
            HttpHeaders headers = request.getHeaders();//获取请求头
            List<String> strings = headers.get("X-Token");
            if(strings != null){ //不等于空说明没登录
                String s = strings.get(0);//取出用户名
                if(s.equals("admin-token")){
                    return chain.filter(exchange);//放行
                }
            }
            //没有登录:重定向到登录页面
            response.setStatusCode(HttpStatus.SEE_OTHER);//没有登录情况下去登录页面看看
            response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:9528");
            response.setComplete();//结束请求
        }
            //直接拦截
            return out(response);
    }

    //錯誤信息提示方法
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject jsonObject=new JsonObject();

        jsonObject.addProperty("code","20001");
        jsonObject.addProperty("message","路径有误");
        jsonObject.addProperty("success","false");
        byte[] bits =jsonObject.toString().getBytes(StandardCharsets.UTF_8);

        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.NOT_FOUND);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //将JSON对象响应给了浏览器端
        return response.writeWith(Mono.just(buffer));
    }


    //影响全局过滤器的执行顺序,值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
